package com.lcz.mq.consumer.listener;

import com.alibaba.fastjson.JSON;
import com.lcz.mq.consumer.MailBiz;
import com.lcz.mq.consumer.bean.MailBean;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.Session;

/**
 * 队列监听器
 * Created by luchunzhou on 2018/3/12.
 */
@Component
public class ConsumerSessionAwareMessageListener implements SessionAwareMessageListener<Message> {

    private static final Log log = LogFactory.getLog(ConsumerSessionAwareMessageListener.class);

    @Autowired
    private MailBiz bailBiz;

    @Override
    public synchronized void onMessage(Message message, Session session) {
        try {
            ActiveMQTextMessage msg = (ActiveMQTextMessage) message;
            final String ms = msg.getText();
            log.info("==>receive message:" + ms);
            // 转换成相应的对象
            MailBean mailParam = JSON.parseObject(ms, MailBean.class);
            if (mailParam == null) {
                return;
            }
            try {
                bailBiz.mailSend(mailParam);
            } catch (Exception e) {
                // 发送异常，重新放回队列
//				activeMqJmsTemplate.send(sessionAwareQueue, new MessageCreator() {
//					public Message createMessage(Session session) throws JMSException {
//						return session.createTextMessage(ms);
//					}
//				});
                log.error("==>MailException:", e);
            }
        } catch (Exception e) {
            log.error("==>", e);
        }
    }
}
